﻿using AutoMapper;
using JTTD.Common.Enum;
using JTTD.DataBase;
using JTTD.DataBase.Model.ShopActivity;
using JTTD.DataBase.Model.ShopCoupon;
using JTTD.Domain.Dtos;
using JTTD.Domain.Dtos.ShopActivity.Request;
using JTTD.Domain.Dtos.ShopActivity.Response;
using JTTD.Domain.IService;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using JTTD.Common.Helper;

namespace JTTD.Domain.Service
{
    /// <summary>
    /// 店铺活动服务
    /// </summary>
    public  class ShopActivityService: IShopActivityService
    {
        private readonly JTTDContext _dbContext;
        private readonly IMapper _mapper;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="dbContext"></param>
        /// <param name="mapper"></param>
        public ShopActivityService(JTTDContext dbContext,IMapper mapper)
        {
            _dbContext = dbContext;
            _mapper = mapper;
        }
        /// <summary>
        /// 设置店铺活动
        /// </summary>
        /// <param name="shopId"></param>
        /// <param name="dto"></param>
        /// <returns></returns>
       public async Task<ApiResult<bool>> SetShopActivity(int shopId,SetShopActivityRequestDto dto)
        {
            try
            {
                if (!string.IsNullOrWhiteSpace(dto.No))
                {
                    var model = await _dbContext.ShopActivityInfoModels.FirstOrDefaultAsync(item => item.No == dto.No.Trim());
                    if (model == null)
                    {
                        return new ApiResult<bool> { IsSuccess = false, Message = "没有找到符合条件的店铺活动" };
                    }
                    model.Name = dto.Name;
                    model.Photo = dto.Photo;
                    model.StartTime = dto.StartTime;
                    model.EndTime = dto.EndTime;
                    model.Type = dto.Type;
                    model.FullAmount = dto.FullAmount;
                    model.CouponAmount = dto.CouponAmount;
                    model.CashCouponAmount = dto.CashCouponAmount;
                    model.Remark = dto.Remark;
                    _dbContext.ShopActivityInfoModels.Update(model);
                }
                else
                {
                    var model = _mapper.Map<ShopActivityInfoModel>(dto);
                    model.ShopId = shopId;
                    model.No ="No" + DateTime.Now.Ticks; 
                    _dbContext.ShopActivityInfoModels.Add(model);
                }
                await _dbContext.SaveChangesAsync();
                return new ApiResult<bool> { IsSuccess = true, Message = "操作成功" };
            }
            catch(Exception ex)
            {
                return new ApiResult<bool> { IsSuccess = true, Message = "操作失败，"+ex.Message };
            }
         
        }

        /// <summary>
        /// 更改店铺活动启用状态
        /// </summary>
        /// <param name="shopActivityId"></param>
        /// <param name="isEnable"></param>
        /// <returns></returns>
       public async  Task<ApiResult<bool>> ChangeEnable(int shopActivityId, bool isEnable)
        {
            try
            {
                var model=await  _dbContext.ShopActivityInfoModels.FindAsync(shopActivityId);
                if(model==null)
                {
                    return new ApiResult<bool> { IsSuccess=false,Message="没有找到符合条件的店铺活动"};
                }
                model.IsEnable = isEnable;
                _dbContext.ShopActivityInfoModels.Update(model);
                await _dbContext.SaveChangesAsync();
                return new ApiResult<bool> { IsSuccess=true,Message="操作成功"};

            }catch(Exception ex)
            {
                return new ApiResult<bool> { IsSuccess=false,Message="操作失败，"+ex.Message};
            }
        }

        /// <summary>
        /// 删除店铺活动
        /// </summary>
        /// <param name="shopActivityId"></param>
        /// <returns></returns>
       public async  Task<ApiResult<bool>> DeleteShopActivity(int shopActivityId)
        {
            try
            {
                var model = await _dbContext.ShopActivityInfoModels.FindAsync(shopActivityId);
                if (model == null)
                {
                    return new ApiResult<bool> { IsSuccess = false, Message = "没有找到符合条件的店铺活动" };
                }
                model.IsDelete = true;
                _dbContext.ShopActivityInfoModels.Update(model);
                await _dbContext.SaveChangesAsync();
                return new ApiResult<bool> { IsSuccess=true,Message="操作成功"};
            }
            catch (Exception ex)
            {
                return new ApiResult<bool> { IsSuccess = false, Message = "操作失败，" + ex.Message };
            }
        }

        /// <summary>
        /// 获取单个店铺活动
        /// </summary>
        /// <param name="shopActivityId"></param>
        /// <returns></returns>
       public async  Task<ApiResult<ShopActivityInfoResponseDto>> GetShopActivity(int shopActivityId)
        {
            var model=await  _dbContext.ShopActivityInfoModels.FindAsync(shopActivityId);
            return new ApiResult<ShopActivityInfoResponseDto> { IsSuccess=true,Data=_mapper.Map<ShopActivityInfoResponseDto>(model)??new ShopActivityInfoResponseDto()};
        }

        /// <summary>
        /// 分页获取店铺活动列表
        /// </summary>
        /// <param name="shopId"></param>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult<PageResult<ShopActivityInfoResponseDto>>> GetShopActivityPageList(int shopId,SearchShopActivityRequestDto dto)
        {
            var query = _dbContext.ShopActivityInfoModels.Where(item=>!item.IsDelete&&item.ShopId==shopId);
            if(!string.IsNullOrWhiteSpace(dto.No))
            {
                query = query.Where(item=>item.No==dto.No.Trim());
            }
            if(!string.IsNullOrWhiteSpace(dto.Name))
            {
                query = query.Where(item=>item.Name==dto.Name.Trim());
            }
            if(dto.Type.HasValue)
            {
                query = query.Where(item=>item.Type==dto.Type.Value);
            }
            int count = await query.CountAsync();
            if(count>0)
            {
                var list = await query.OrderByDescending(item => item.No).Skip((dto.PageIndex - 1) * dto.PageSize).Take(dto.PageSize).ToListAsync();
                return new ApiResult<PageResult<ShopActivityInfoResponseDto>>()
                {
                    Data = new PageResult<ShopActivityInfoResponseDto>()
                    {
                        Data = _mapper.Map<List<ShopActivityInfoResponseDto>>(list),
                        PageIndex = dto.PageIndex,
                        PageSize = dto.PageSize,
                        TotalNum = count,
                        TotalPageNum = (count % dto.PageSize) == 0 ? count / dto.PageSize : count / dto.PageSize + 1
                    },
                    IsSuccess = true

                };
            }
            else
            {
                return new ApiResult<PageResult<ShopActivityInfoResponseDto>>()
                {
                    Data = new PageResult<ShopActivityInfoResponseDto>()
                    {
                        PageIndex = dto.PageIndex,
                        PageSize = dto.PageSize,
                        Data = new List<ShopActivityInfoResponseDto>()
                    },
                    IsSuccess = true,
                    Message = "查询成功，暂无数据"
                };
            }
        }

        /// <summary>
        /// 获取启用进行中的店铺活动
        /// </summary>
        /// <param name="shopId"></param>
        /// <returns></returns>
        public async Task<ApiResult<List<ShopActivityInfoResponseDto>>> GetEnableShopActivityList(int shopId)
        {
            var list=await _dbContext.ShopActivityInfoModels.Where(item => item.ShopId == shopId&& item.StartTime <= DateTime.Now && DateTime.Now <= item.EndTime&&item.IsEnable&&!item.IsDelete)
                .OrderByDescending(item => item.No).ToListAsync();
            return new ApiResult<List<ShopActivityInfoResponseDto>> { IsSuccess=true,Data=_mapper.Map<List<ShopActivityInfoResponseDto>>(list)??new List<ShopActivityInfoResponseDto>()};
        }

        /// <summary>
        /// 参与店铺活动
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="shopActivityId"></param>
        /// <returns></returns>
        public  async  Task<ApiResult<bool>> JoinShopActivity(int userId, int shopActivityId)
        {
            try
            {
                var user = await _dbContext.UserInfos.FindAsync(userId);
                if (user == null)
                {
                    return new ApiResult<bool> { IsSuccess = false, Message = "没有找到指定用户" };
                }
                var shopActivity = await _dbContext.ShopActivityInfoModels.FindAsync(shopActivityId);
                if (shopActivity == null)
                {
                    return new ApiResult<bool> { IsSuccess = false, Message = "没有找到指定店铺活动" };
                }
                if (!(shopActivity.StartTime <= DateTime.Now && DateTime.Now <= shopActivity.EndTime && shopActivity.IsEnable && !shopActivity.IsDelete))
                {
                    return new ApiResult<bool> { IsSuccess = false, Message = "当前活动已过期" };
                }
                int existsCount = await _dbContext.ShopActivityJoinUserModels.CountAsync(item => item.ShopActivityId == shopActivityId && item.UserId == userId);
                if (existsCount > 0)
                {
                    return new ApiResult<bool> { IsSuccess = false, Message = "您已经参加过本次活动" };
                }
                var config = await _dbContext.ConfigInfoModels.FirstOrDefaultAsync(item => item.Key == ConfigTypeEnum.ShopCouponOutTimeDayNum);
                if (config == null)
                {
                    return new ApiResult<bool> { IsSuccess = false, Message = $"{ConfigTypeEnum.ShopCouponOutTimeDayNum.GetDescription()}配置尚未初始化" };
                }
                _dbContext.Database.BeginTransaction();
                _dbContext.ShopActivityJoinUserModels.Add(new ShopActivityJoinUserModel { UserId = userId, ShopActivityId = shopActivityId });
                _dbContext.ShopCouponInfoModels.Add(new ShopCouponInfoModel
                {
                    StartTime = DateTime.Now,
                    EndTime = DateTime.Now.AddDays(Convert.ToInt16(config.Value)),
                    Type = shopActivity.Type == ShopActivityTypeEnum.Coupon ? ShopCouponTypeEnum.FullReduction : ShopCouponTypeEnum.CashCoupon,
                    FullAmount = shopActivity.FullAmount,
                    CouponAmount = shopActivity.Type == ShopActivityTypeEnum.Coupon ? shopActivity.CouponAmount : shopActivity.CashCouponAmount,
                    CreateTime = DateTime.Now,
                    UserId = userId,
                    IsUse = false,ShopId=shopActivity.ShopId
                });
                await _dbContext.SaveChangesAsync();
                _dbContext.Database.CommitTransaction();
                return new ApiResult<bool> { IsSuccess = true, Message = "操作成功" };
            }
            catch(Exception ex)
            {
                return new ApiResult<bool> { IsSuccess=false,Message="操作失败，"+ex.Message};
            }
           
        }
    }
}
